package pl.uz.zgora.plan;

import java.io.IOException;
import java.util.ArrayList;

import org.ksoap2.SoapFault;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

public class SelectTeacherDataActivity extends Activity {
	
	private SOAPManager  mSoapManager = null;
	private ArrayList<String> teachersNames = new ArrayList<String>();
	final private ArrayList<Nauczyciel> teachersList = new ArrayList<Nauczyciel>();
	final private ArrayList<Wydzial> departmentsList = new ArrayList<Wydzial>();
	private ProgressDialog mProgressDialog = null;
	private Nauczyciel selectedTeacher = null;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.select_teacher_data_view);
        
        PrefrencesManager pm =  PrefrencesManager.getInstance(getBaseContext());
		pm.addBooleanToPreferences("hasData", false);
        
        if(HelperMethodsManager.isOnline(this)) {
        	mSoapManager = new SOAPManager(this);
        	mProgressDialog = HelperMethodsManager.getProgressDialog(this);
        	mProgressDialog.show();

        	Thread handleActivity = new Thread(new Runnable() {
        		public void run() {
        			try {
        				final String[] facultiesNames = mSoapManager.downloadDepartmentsList(departmentsList);
        				manageFacultiesUI(facultiesNames);
        			} catch (SoapFault e) {
        				mProgressDialog.dismiss();
        				HelperMethodsManager.manageException("SelectTeacherDataActivity::setupUI()", "SoapFault", e.getLocalizedMessage(), SelectTeacherDataActivity.this);
        			} catch (IOException e) {
        				mProgressDialog.dismiss();
        				HelperMethodsManager.manageException("SelectTeacherDataActivity::setupUI()", "IOException", e.getLocalizedMessage(), SelectTeacherDataActivity.this);
        			} catch (XmlPullParserException e) {
        				mProgressDialog.dismiss();
        				HelperMethodsManager.manageException("SelectTeacherDataActivity::setupUI()", "XmlPullParserException", e.getLocalizedMessage(), SelectTeacherDataActivity.this);
        			}
        		}
        	});

        	handleActivity.start();
        	
        } else {
        	Dialog errorDialog = HelperMethodsManager.getConnectionErrorDialog(this, this);
        	errorDialog.show();
        }
	}
	
	private void manageTeachersUI(ArrayList<String> teachersNames) {
		final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, teachersNames);
		
		final TextView tv_teacher_label = (TextView) findViewById(R.id.tv_teacher_label);
		final ListView teachersListView = (ListView) findViewById(R.id.select_teacher_list);
		final LinearLayout mainLayout = (LinearLayout) findViewById(R.id.select_teacher_data_layout);
		
		TextWatcher inputTextWatcher = new TextWatcher() {
		    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		    	
		    }
		    public void onTextChanged(CharSequence s, int start, int before, int count) {
		    	adapter.getFilter().filter(s);
				adapter.notifyDataSetChanged();    
		    }
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}
		};

		
		final EditText teachersSearchField = (EditText) findViewById(R.id.select_teacher_search_field);
		teachersSearchField.addTextChangedListener(inputTextWatcher);
		
		teachersSearchField.setOnKeyListener(new OnKeyListener() {
			
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				adapter.getFilter().filter(teachersSearchField.getText());
				adapter.notifyDataSetChanged();
				
				return false;
			}
		});
		
		teachersListView.setOnItemClickListener(new OnItemClickListener() {
			
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				String selectedTeacherName = adapter.getItem(position);
				
				int teacherPos = 0;
				for(Nauczyciel nauczyciel: teachersList) {
					
					if(nauczyciel.getNazwa().equals(selectedTeacherName)) {
						break;
					}
					
					teacherPos++;
				}
				
				selectedTeacher = teachersList.get(teacherPos);

				final Intent intent = new Intent(view.getContext(), ClickTipViewActivity.class);
				intent.putExtra("idNauczyciela", selectedTeacher.getIdNauczyciela());
				intent.putExtra("nazwaNauczyciela", selectedTeacher.getNazwa());
				
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				
				try {
					// Wyświetlenie menu głównego
					startActivity(intent);
					setResult(0);
					finish();
				} catch (android.content.ActivityNotFoundException e) {
					HelperMethodsManager.manageException("SelectTeacherDataActivity::setupUI()", e.getLocalizedMessage(), SelectTeacherDataActivity.this);
				}
				
			}
		});
		
		mainLayout.post(new Runnable() {
			
			public void run() {
				
				mProgressDialog.dismiss();
				teachersListView.setAdapter(adapter);
				teachersListView.setVisibility(View.VISIBLE);
				tv_teacher_label.setVisibility(View.VISIBLE);
			}
		});
	}
	
	public void manageFacultiesUI(final String[] facultiesNames) {
		final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, facultiesNames);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		final LinearLayout mainLayout = (LinearLayout) findViewById(R.id.select_teacher_data_layout);
		final TextView tv_department_label = (TextView) findViewById(R.id.tv_department_label);
		final TextView tv_teacher_label = (TextView) findViewById(R.id.tv_teacher_label);
		final ListView teachersListView = (ListView) findViewById(R.id.select_teacher_list);
		final Spinner facultiesSpinner = (Spinner) findViewById(R.id.spinnerFaculties);
		
		
		facultiesSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> parent, View view,
					final int pos, long id) {
				
				Thread handleActivity = new Thread(new Runnable() {

					public void run() {
						try {
							
							mainLayout.post(new Runnable() {

								public void run() {
									tv_teacher_label.setVisibility(View.INVISIBLE);
									mProgressDialog.show();
									teachersListView.setVisibility(View.INVISIBLE);
								}
							});
							
							teachersNames = mSoapManager.downloadTeachersForDepartment(departmentsList.get(pos).getId(), teachersList);
							
							
							manageTeachersUI(teachersNames);
							
						} catch (SoapFault e) {
							mProgressDialog.dismiss();
							HelperMethodsManager.manageException("SelectTeacherDataActivity::setupUI()", "SoapFault",  e.getLocalizedMessage(), SelectTeacherDataActivity.this);
						} catch (IOException e) {
							mProgressDialog.dismiss();
							HelperMethodsManager.manageException("SelectTeacherDataActivity::setupUI()", "IOException", e.getLocalizedMessage(), SelectTeacherDataActivity.this);
						} catch (XmlPullParserException e) {
							mProgressDialog.dismiss();
							HelperMethodsManager.manageException("SelectTeacherDataActivity::setupUI()", "XmlPullParserException", e.getLocalizedMessage(), SelectTeacherDataActivity.this);
						}
					}});
				handleActivity.start();
			}

			public void onNothingSelected(AdapterView<?> parent) {
			}
		});
		
		
		mainLayout.post(new Runnable() {
			
			public void run() {
				mProgressDialog.dismiss();
				tv_department_label.setVisibility(View.VISIBLE);
				facultiesSpinner.setVisibility(Spinner.VISIBLE);
				facultiesSpinner.setAdapter(adapter);
				
			}
		});
	}
}
